//
//  LittleBallPropertyViewController.m
//  LittleBall
//
//  Created by  on 12-5-6.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "LittleBallPropertyViewController.h"
#import "LittleBallPlayViewController.h"
#import "LittleBallGameManagement.h"


@implementation LittleBallPropertyViewController

@synthesize m_playViewController;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
//    m_viewGroup1.hidden = false;
//
//    [m_viewFrame addSubview:m_viewGroup1];
    
//    m_currentGroupId = 0;
    m_selectedIndexId = LB_PROPERTY_UNSELECTED_ID;
    m_selectedGroupId = LB_PROPERTY_UNSELECTED_ID;
    
    // 初始化Group
    [self initGroups];
}

- (void)viewDidUnload
{
    [self savePropertiesData];
    
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	return YES;
}

//- (IBAction)onButton_group1:(id)sender
//{
//    m_viewGroup2.hidden = true;
//    m_viewGroup1.hidden = false;
//    
//    [m_viewGroup2 removeFromSuperview];
//    [m_viewFrame addSubview:m_viewGroup1];
//    m_currentGroupId = 0;
//}
//
//- (IBAction)onButton_group2:(id)sender
//{
//    m_viewGroup1.hidden = true;
//    m_viewGroup2.hidden = false;
//    
//    [m_viewGroup1 removeFromSuperview];
//    [m_viewFrame addSubview:m_viewGroup2];
//    m_currentGroupId = 1;
//}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches] anyObject];
    LittleBallPlayViewController *playViewController = m_playViewController;
    
    CGPoint    touchPoint = [touch locationInView:self.view];
    for (int groupId = 0; groupId < LB_PROPERTIES_GROUPNUM; groupId++)
    {    
        for (int sizeIndex = 0; sizeIndex < LB_PROPERTIES_GROUPSIZE; sizeIndex++)
        {
            LBPropertyUnit *unit = m_propertyUnit[groupId][sizeIndex];

            CGPoint centerTmp = unit.m_centerPoint;
            if (centerTmp.x - LB_PROPERTY_UNIT_WIDTH/2 < touchPoint.x
                && centerTmp.x + LB_PROPERTY_UNIT_WIDTH/2 > touchPoint.x
                && centerTmp.y - LB_PROPERTY_UNIT_HEIGHT/2 < touchPoint.y
                && centerTmp.y + LB_PROPERTY_UNIT_HEIGHT/2 > touchPoint.y
                && unit.m_propertyNum > 0 ) // 可用个数必须大于0才能被选中 
            {
                // 先把之前选定的去除标记
                if ( m_selectedIndexId != LB_PROPERTY_UNSELECTED_ID ) 
                {
                    LBPropertyUnit *unitTmp = m_propertyUnit[m_selectedGroupId][m_selectedIndexId];
                    unitTmp.m_backgroundImageView.image = m_background_unit_normal;
                }
                
                // 如果点在当前已选定的道具上面，则取消选定
                if( m_selectedGroupId == groupId
                    && m_selectedIndexId == sizeIndex )
                {
                    m_selectedGroupId = LB_PROPERTY_UNSELECTED_ID;
                    m_selectedIndexId = LB_PROPERTY_UNSELECTED_ID;
                }
                else
                {
                    // 再标记已选定的
                    m_selectedGroupId = groupId;
                    m_selectedIndexId = sizeIndex;
                    
                    unit.m_backgroundImageView.image = m_background_unit_selected;
                }
                
                break;
            }
        }
    }

    if ( m_selectedIndexId != LB_PROPERTY_UNSELECTED_ID )  // 选中了某个道具
    {
        [playViewController unSelectBall];
    }
}

- (void)initGroups
{
    [self initImages];
    
    CGPoint centerPoint = CGPointMake(LB_PROP_UNIT_COORDINATE_START_X+LB_PROPERTY_UNIT_WIDTH/2, LB_PROP_UNIT_COORDINATE_START_Y+LB_PROPERTY_UNIT_HEIGHT/2);
    
    //UIView *m_viewGroupTmp = nil;

    [m_viewFrame setBounds:CGRectMake(0, 0, LB_PROP_UNIT_COORDINATE_START_X*2+LB_PROPERTY_UNIT_WIDTH*LB_PROPERTIES_GROUPSIZE, LB_PROP_UNIT_COORDINATE_START_Y*2+(LB_PROPERTY_UNIT_HEIGHT*1.5)*LB_PROPERTIES_GROUPNUM)];
        
    [m_viewFrame setCenter:CGPointMake(COORDINATE_START_X+m_viewFrame.bounds.size.width/2, COORDINATE_START_Y+MAX_ROW*BALL_HEIGHT+m_viewFrame.bounds.size.height/2)];
    
    for (int numIndex = 0; numIndex < LB_PROPERTIES_GROUPNUM; numIndex++) 
    {
        for (int sizeIndex = 0; sizeIndex < LB_PROPERTIES_GROUPSIZE; sizeIndex++)
        {         
            LBPropertyUnit *unit = [[LBPropertyUnit alloc] init];
            m_propertyUnit[numIndex][sizeIndex] = unit;
            
            // Begin // 初始化背景图像 //
            UIImageView *backgroundUnit = [[UIImageView alloc] initWithImage:m_background_unit_normal];
            
            unit.m_backgroundImageView = backgroundUnit;
            
            backgroundUnit.center = centerPoint;
            unit.m_centerPoint = centerPoint;
            [m_viewFrame addSubview:backgroundUnit];         
            centerPoint.x += LB_PROPERTY_UNIT_WIDTH;
            // End // 初始化背景图像 //
            
            UIImage *image = nil;
        
            // Begin // 根据存档加载道具 //////////////////////////////////////////////
            LittleBallPlayViewController *playViewController = m_playViewController;
            LittleBallGameManagement    *gameManagement = playViewController.m_gameManagement;
            LBData *data = gameManagement.gameData;
            NSMutableArray *propertiesTmp = data.properties;
            LBPropertyUnit *unitTmp = [propertiesTmp objectAtIndex:(numIndex*LB_PROPERTIES_GROUPSIZE+sizeIndex)];
            
            unit.m_propertyType = unitTmp.m_propertyType;
            unit.m_propertyLevel = unitTmp.m_propertyLevel;
            unit.m_propertyNum = unitTmp.m_propertyNum;
            unit.m_propertyValue = unitTmp.m_propertyValue;
            image = m_propertiesImageArray[unit.m_propertyType];
            // End // 根据存档加载道具 //////////////////////////////////////////////

            // Begin // 道具图标显示 ///////////////////////////////////////////////
            unit.m_propertyImageView = [[UIImageView alloc] initWithImage: image];
            unit.m_propertyImageView.center =unit.m_centerPoint;

            // Level Lable
            unit.m_levelLable = [[UILabel alloc] initWithFrame:CGRectMake(-2, -4, 16, 16)];
            unit.m_levelLable.font = [unit.m_levelLable.font fontWithSize:14];
            unit.m_levelLable.textColor = [UIColor colorWithRed:0.1 green:0.2 blue:0.3 alpha:1];
            unit.m_levelLable.backgroundColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0];
            unit.m_levelLable.shadowColor = [UIColor colorWithRed:0.8 green:0.9 blue:1.0 alpha:1];
            unit.m_levelLable.shadowOffset = CGSizeMake(1, 1);
            [unit.m_levelLable setText:[NSString stringWithFormat:@"L%d",unit.m_propertyLevel]];
            [unit.m_propertyImageView addSubview:unit.m_levelLable];

            // Number Lable
            unit.m_numLable = [[UILabel alloc] initWithFrame:CGRectMake(LB_PROPERTY_UNIT_WIDTH-36, LB_PROPERTY_UNIT_HEIGHT-26, 40, 16)];
            unit.m_numLable.font = [unit.m_numLable.font fontWithSize:14];
            unit.m_numLable.textColor = [UIColor colorWithRed:0.1 green:0.2 blue:0.3 alpha:1];
            unit.m_numLable.backgroundColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0];
            unit.m_numLable.shadowColor = [UIColor colorWithRed:0.8 green:0.9 blue:1.0 alpha:1];
            unit.m_numLable.shadowOffset = CGSizeMake(1, 1);
            [unit.m_numLable setText:[NSString stringWithFormat:@"x%02d",unit.m_propertyNum]];
            [unit.m_propertyImageView addSubview:unit.m_numLable];
            
            [m_viewFrame addSubview:unit.m_propertyImageView];
            // End // 道具图标显示 ///////////////////////////////////////////////
            
            // Begin // 道具即时购买按钮 ///////////////////////////////////////////////
            GLuint propertyBackgroundImageHeight = unit.m_backgroundImageView.frame.size.height;
            GLuint buttonHeight = propertyBackgroundImageHeight/2+4;
            GLuint buttonWidth = unit.m_backgroundImageView.frame.size.width+8;
            
            unit.m_buyButton = [UIButton buttonWithType:UIButtonTypeCustom];
            [unit.m_buyButton setFrame:CGRectMake(0, 0, buttonWidth, buttonHeight)];
            unit.m_buyButton.titleLabel.font = [unit.m_buyButton.titleLabel.font fontWithSize:14];
            
            NSString  *buttonTittle = [NSString stringWithFormat:@"%d两银",unit.m_propertyValue];
            [unit.m_buyButton setTitle:buttonTittle forState:UIControlStateNormal];
            
            unit.m_buyButton.center = CGPointMake(unit.m_centerPoint.x, unit.m_centerPoint.y+propertyBackgroundImageHeight/2+buttonHeight/2);
            [unit.m_buyButton addTarget:self action:@selector(onButton_buy:) forControlEvents:UIControlEventTouchDown];
            
            //unit.m_buyButton.backgroundColor = [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1];
            [unit.m_buyButton setTitleColor:[UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1] forState:UIControlStateDisabled];
            [unit.m_buyButton setTitleColor:[UIColor colorWithRed:0.1 green:0.2 blue:0.3 alpha:1] forState:UIControlStateNormal];
            [unit.m_buyButton setBackgroundImage:m_buttonImg_disable forState:UIControlStateDisabled];
            [unit.m_buyButton setBackgroundImage:m_buttonImg_normal forState:UIControlStateNormal];
            [unit.m_buyButton setBackgroundColor:[UIColor colorWithRed:0.1 green:0.2 blue:0.3 alpha:0]];
            //unit.m_buyButton.titleLabel.textColor = ;
            unit.m_buyButton.adjustsImageWhenDisabled = YES;
            //unit.m_buyButton.opaque = NO;
            // End // 道具即时购买按钮 ///////////////////////////////////////////////
            
            [m_viewFrame addSubview:unit.m_buyButton];            
        }
        centerPoint.y += LB_PROPERTY_UNIT_HEIGHT+LB_PROPERTY_UNIT_HEIGHT/2;
        centerPoint.x = LB_PROP_UNIT_COORDINATE_START_X+LB_PROPERTY_UNIT_WIDTH/2;    
    }
    
    [self checkAndChangeBuyButtonsState];
}

- (void)initImages
{
    NSString *unitImgPath = [[NSBundle mainBundle] pathForResource:@"play_background_unit" ofType:@"png"];
    m_background_unit_normal = [[UIImage alloc] initWithContentsOfFile:unitImgPath];
    
    unitImgPath = [[NSBundle mainBundle] pathForResource:@"play_background_unit_yellow" ofType:@"png"];
    m_background_unit_selected = [[UIImage alloc] initWithContentsOfFile:unitImgPath];
    
    /*---------------------------------------------*/
    
    NSString *propertyImgPath = [[NSBundle mainBundle] pathForResource:@"bomb" ofType:@"png"];
    m_propertiesImageArray[LB_PROPERTY_BOMB] = [[UIImage alloc] initWithContentsOfFile:propertyImgPath];
    
    propertyImgPath = [[NSBundle mainBundle] pathForResource:@"colorBall" ofType:@"png"];
    m_propertiesImageArray[LB_PROPERTY_COLORBALL] = [[UIImage alloc] initWithContentsOfFile:propertyImgPath];
    
    /*---------------------------------------------*/
    
    NSString *byButtonImgPath = [[NSBundle mainBundle] pathForResource:@"button_buy_disable" ofType:@"png"];
    m_buttonImg_disable = [[UIImage alloc] initWithContentsOfFile:byButtonImgPath];
    
    byButtonImgPath = [[NSBundle mainBundle] pathForResource:@"button_buy_normal" ofType:@"png"];
    m_buttonImg_normal = [[UIImage alloc] initWithContentsOfFile:byButtonImgPath];
    
}

- (BOOL)isPropertySelected
{
    return m_selectedIndexId == LB_PROPERTY_UNSELECTED_ID?false:true;
}

- (void)resetPropertyState
{
    if( [self isPropertySelected] )
    {
        LBPropertyUnit *unit = m_propertyUnit[m_selectedGroupId][m_selectedIndexId];
        
        unit.m_backgroundImageView.image = m_background_unit_normal;
        if( unit.m_propertyNum > 0)
        {
            unit.m_propertyNum--;
        }
        [unit.m_numLable setText:[NSString stringWithFormat:@"x%02d",unit.m_propertyNum]];
        
        m_selectedGroupId = LB_PROPERTY_UNSELECTED_ID;
        m_selectedIndexId = LB_PROPERTY_UNSELECTED_ID;
    }
}

- (LB_PROPERTY_TYPE)getPropertyType
{
    if ([self isPropertySelected]) 
    {
        LBPropertyUnit *unit = m_propertyUnit[m_selectedGroupId][m_selectedIndexId];
        return unit.m_propertyType;
    }
    
    return LB_PROPERTY_MAX;
}

- (int)getPropertyLevel
{
    if ([self isPropertySelected]) 
    {
        LBPropertyUnit *unit = m_propertyUnit[m_selectedGroupId][m_selectedIndexId];
        return unit.m_propertyLevel;
    }
    
    return 0;
}

// 道具即时购买的响应函数
- (IBAction)onButton_buy:(id)sender
{
    for (int groupId = 0; groupId < LB_PROPERTIES_GROUPNUM; groupId++)
    {    
        for (int sizeIndex = 0; sizeIndex < LB_PROPERTIES_GROUPSIZE; sizeIndex++)
        {
            LBPropertyUnit *unit = m_propertyUnit[groupId][sizeIndex];
            
            if( sender == unit.m_buyButton )
            {
                LittleBallPlayViewController *playViewController = m_playViewController;
                
                if ( playViewController.gameScore >= unit.m_propertyValue ) 
                {
                    playViewController.gameScore -= unit.m_propertyValue;                    
                    unit.m_propertyNum++;
                    
                    [playViewController refreshScoreDisplay];
                    [unit.m_numLable setText:[NSString stringWithFormat:@"x%02d",unit.m_propertyNum]];
                    [self savePropertiesData];
                    
                    return;
                }
                
            }
        }
    }
}

- (void)savePropertiesData
{
    LittleBallPlayViewController *playViewController = m_playViewController;
    LittleBallGameManagement    *gameManagement = playViewController.m_gameManagement;
    LBData *data = gameManagement.gameData;
    NSMutableArray *propertiesTmp = data.properties;
    [propertiesTmp removeAllObjects];
    
    for (int groupId = 0; groupId < LB_PROPERTIES_GROUPNUM; groupId++)
    {    
        for (int sizeIndex = 0; sizeIndex < LB_PROPERTIES_GROUPSIZE; sizeIndex++)
        {
            LBPropertyUnit *unit = m_propertyUnit[groupId][sizeIndex];

            [propertiesTmp addObject:unit];
            [gameManagement WriteDataIntoFile];            
        }
    }
    
}

- (void)checkAndChangeBuyButtonsState
{
    LittleBallPlayViewController *playViewController = m_playViewController;
    //LittleBallGameManagement    *gameManagement = playViewController.m_gameManagement;
    //LBData *data = gameManagement.gameData;
    
    for (int groupId = 0; groupId < LB_PROPERTIES_GROUPNUM; groupId++)
    {    
        for (int sizeIndex = 0; sizeIndex < LB_PROPERTIES_GROUPSIZE; sizeIndex++)
        {
            LBPropertyUnit *unit = m_propertyUnit[groupId][sizeIndex];
            
            if( playViewController.gameScore >= unit.m_propertyValue )
            {
                // 设置按钮状态为可以购买
                unit.m_buyButton.enabled = YES; // 设置按钮不可用
            }
            else 
            {
                // 设置按钮状态为不能购买
                unit.m_buyButton.enabled = NO; // 设置按钮不可用
            }
        }
    }
}

@end
